package com.wei;

/**
 * 测试捕获线程中断,线程中断时会触发钩子,
 *
 * @author :sunwei
 * @description:
 * @date create in 22:39  2021/6/17
 */
public class RuntimeShutdownHookTest {
    
    public static void main(String[] args) {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                Thread.sleep(1_000);
            } catch (InterruptedException e) {
            }
            System.out.println("notify the admin...");
            
            try {
                Thread.sleep(1_000);
            } catch (InterruptedException e) {
            }
            System.out.println("release all resources...");
        }));
    
        workWithAnException();
        
    }
    
    public static void workWithAnException() {
        new Thread(() -> {
            int i = 0;
            while (true) {
                
                try {
                    System.out.println("i am working...");
                    Thread.sleep(1_000);
                } catch (InterruptedException e) {
                }
                i++;
                if(i>=10){
                    throw new RuntimeException("occur an exception ,i am shutdown...");
                }
            }
        }).start();
    }
}
